package cn.zhejianglao.shirotemplate.service.menu.service;

import cn.zhejianglao.shirotemplate.common.model.MenuVO;
import cn.zhejianglao.shirotemplate.exception.BusinessException;
import cn.zhejianglao.shirotemplate.exception.ExceptionCode;
import cn.zhejianglao.shirotemplate.service.menu.dao.IMenuMapper;
import cn.zhejianglao.shirotemplate.service.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuService implements IMenuService {

    @Autowired
    private IMenuMapper menuMapper;

    @Autowired
    private IUserService userService;

    @Override
    public List<MenuVO> list(int parentId) {
        Long currentRoleId = userService.getCurrentUser().getCurrentRoleId();
        return menuMapper.selectByParentIdAndRoleId(parentId, currentRoleId);
    }

    @Override
    public void create(MenuVO vo) {
        Long parentId = vo.getParentId();
        if (parentId != 0 && menuMapper.selectCountById(parentId) == 0) {
            throw new BusinessException(
                    ExceptionCode.Common.RESOURCE_NOT_EXISTS_CODE,
                    ExceptionCode.Common.RESOURCE_NOT_EXISTS_MSG
            );
        }
        if (menuMapper.selectCountByNameAndParentId(vo) > 0) {
            throw new BusinessException(
                    ExceptionCode.Common.RESOURCE_ALREADY_EXISTS_CODE,
                    ExceptionCode.Common.RESOURCE_ALREADY_EXISTS_MSG
            );
        }
        initLevel(vo, parentId);
        Long userId = userService.getCurrentUser().getId();
        vo.setCreatedBy(userId);
        menuMapper.insert(vo);
    }

    @Override
    public void delete(Long id) {
        menuMapper.deleteById(id);
    }

    @Override
    public void update(MenuVO vo) {
        Long parentId = vo.getParentId();
        if (menuMapper.selectCountById(vo.getId()) == 0 ||
                (parentId != 0 && menuMapper.selectCountById(parentId) == 0)) {
            throw new BusinessException(
                    ExceptionCode.Common.RESOURCE_NOT_EXISTS_CODE,
                    ExceptionCode.Common.RESOURCE_NOT_EXISTS_MSG
            );
        }
        initLevel(vo, parentId);
        Long userId = userService.getCurrentUser().getId();
        vo.setModifiedBy(userId);
        menuMapper.update(vo);
    }

    /**
     * 为菜单对象初始化层级
     *
     * @param vo 菜单对象
     * @param parentId 父结点id
     */
    private void initLevel(MenuVO vo, long parentId) {
        if (parentId == 0) {
            vo.setLevel(1);
        } else {
            vo.setLevel(menuMapper.selectLevelById(parentId) + 1);
        }
    }
}
